﻿using FictionsDownload.Migrations;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FictionsDownload.Static
{
    class AccessAppSettings
    {
        private static System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        public static void Add(string key,string value)
        {
            config.AppSettings.Settings.Add(key, value);
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
        public static string Get(string key)
        {
            try
            {
                return config.AppSettings.Settings[key].Value;
            }
            catch(Exception ex)
            {
                if(ex.Message == "未将对象引用设置到对象的实例。")
                {
                    return null;
                }
                else
                {
                    return null;
                }
            }
        }
        public static void Update(string key,string value)
        {
            try
            {
                config.AppSettings.Settings[key].Value = value;
                //一定要记得保存，写不带参数的config.Save()也可以
                config.Save(ConfigurationSaveMode.Modified);
                //刷新，否则程序读取的还是之前的值（可能已装入内存）
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                if (ex.Message == "未将对象引用设置到对象的实例。")
                {
                    Add(key,  value);
                }
                else
                {
                    Add(key,  value);
                }
            }
        }
        public static void Delete(string key)
        {
            config.AppSettings.Settings.Remove(key);
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
